module.exports = (sequelize, DataTypes) => {
  const Diary = sequelize.define('Diary', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    user_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'users',
        key: 'id'
      }
    },
    category_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'categories',
        key: 'id'
      }
    },
    title: {
      type: DataTypes.STRING(200),
      allowNull: false,
      validate: {
        len: [1, 200],
        notEmpty: true
      }
    },
    content: {
      type: DataTypes.TEXT('long'),
      allowNull: false,
      validate: {
        notEmpty: true
      }
    },
    diary_date: {
      type: DataTypes.DATEONLY,
      allowNull: false,
      validate: {
        isDate: true
      }
    },
    weather: {
      type: DataTypes.STRING(20),
      allowNull: true,
      validate: {
        len: [0, 20]
      }
    },
    mood: {
      type: DataTypes.STRING(20),
      allowNull: true,
      validate: {
        len: [0, 20]
      }
    },
    is_public: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    },
    view_count: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      validate: {
        min: 0
      }
    }
  }, {
    tableName: 'diaries',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    charset: 'utf8mb4',
    collate: 'utf8mb4_general_ci',
    indexes: [
      {
        fields: ['user_id']
      },
      {
        fields: ['category_id']
      },
      {
        fields: ['diary_date']
      },
      {
        fields: ['created_at']
      },
      {
        fields: ['user_id', 'diary_date'],
        name: 'idx_diaries_user_date'
      },
      {
        fields: ['is_public']
      }
    ]
  });

  Diary.associate = (models) => {
    // 日记属于用户
    Diary.belongsTo(models.User, {
      foreignKey: 'user_id',
      as: 'user',
      onDelete: 'CASCADE'
    });

    // 日记属于分类
    Diary.belongsTo(models.Category, {
      foreignKey: 'category_id',
      as: 'category',
      onDelete: 'SET NULL'
    });

    // 日记与标签多对多关联
    Diary.belongsToMany(models.Tag, {
      through: models.DiaryTag,
      foreignKey: 'diary_id',
      otherKey: 'tag_id',
      as: 'tags',
      onDelete: 'CASCADE'
    });

    // 日记有多张图片
    Diary.hasMany(models.Image, {
      foreignKey: 'diary_id',
      as: 'images',
      onDelete: 'CASCADE'
    });
  };

  // 实例方法：增加浏览次数
  Diary.prototype.incrementViewCount = function() {
    return this.increment('view_count');
  };

  return Diary;
}; 